﻿using System;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Linq;

namespace EnetaMvc.Web.Extensions
{
    public static class Util
    {
        private static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);

        public static string StripTags(string source)
        {
            if (source == null)
                return null;

            return _htmlRegex.Replace(source, string.Empty);
        }

        public static string StripForbiddenTags(string source)
        {
            var forbiddenTags = new[] { "style","script" };

            foreach (var forbiddenTag in forbiddenTags)
            {
                source = Regex.Replace(source, "<" + forbiddenTag + ">(.|\n)*?</" + forbiddenTag + ">", string.Empty, RegexOptions.IgnoreCase);
            }

            return source;
        }

        /// <summary>
        /// Remove HTML tags from string using char array.
        /// </summary>
        public static string StripAllHtmlTags(this HtmlHelper helper, string source)
        {
            char[] array = new char[source.Length];
            int arrayIndex = 0;
            bool inside = false;

            for (int i = 0; i < source.Length; i++)
            {
                char let = source[i];
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (!inside)
                {
                    array[arrayIndex] = let;
                    arrayIndex++;
                }
            }
            return new string(array, 0, arrayIndex);
        }

        public static string ActiveMenuItemClass(this HtmlHelper helper, params string[] controllerNames)
        {
            string currentController = helper.ViewContext.RouteData.Values["controller"].ToString();
            foreach (string str in controllerNames)
                if (currentController.Equals(str, StringComparison.InvariantCultureIgnoreCase))
                    return "active";
            return "";
        }

        public static string ActiveMenuItemClassForUrl(this HtmlHelper helper, string url)
        {
            if (!url.StartsWith("~/") || url.Where(x=> x == '/').Count() < 2)
                return "";

            string controllerFromUrl = url.Substring(2, url.IndexOf("/", 2) - 2);
            string currentController = helper.ViewContext.RouteData.Values["controller"].ToString();
            if (currentController.Equals(controllerFromUrl, StringComparison.InvariantCultureIgnoreCase))
                return "active";
            return "";
        }
    }
}